<template>
  <div class="content-box" v-loading="isLoadIframe">
    <iframe v-for="item in iframeUrls" :key="item.src" v-show="$route.meta.orgin + $route.meta.pathName === item.src"
      class="item" :class="{ cover_item: isCoverIframe }" :src="item.src" frameborder="0" :name="item.iframeName"
      id="content" ref="content" @load="postMsg" seamless>
      loading...
    </iframe>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import NProgress from 'nprogress';
export default {
  data() {
    return {
      src: undefined,
      isLoadIframe: false, // Iframe是否加载完成
      isCoverIframe: false, // Iframe是否全屏
      iframeUrls: [],
    };
  },
  computed: {
    ...mapState(['isCollapse']),
  },
  watch: {
    $route() {
      this.init();
    },
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg);
    this.init();
  },
  methods: {
    // iframe首次加载完毕执行
    postMsg() {
      const { path, name } = this.$route;
      this.sendMessage({ path, name });
      NProgress.done();
      this.isLoadIframe = false;
    },
    init() {
      NProgress.start();
      this.isLoadIframe = true;
      const { path, name, meta } = this.$route;
      const { orgin, pathName } = meta;
      if (this.src === `${orgin}${pathName}`) {
        // this.sendMessage({ path, name });
        this.postMsg()
      } else {
        this.src = `${orgin}${pathName}`;
        if (this.iframeUrls.find(v => v.src === this.src)) {
          // this.sendMessage({ path, name });
          this.postMsg()
        } else {
          this.iframeUrls.push({
            src: this.src,
            iframeName: this.$route.meta.pathName,
          });
        }
      }
    },
    sendMessage(msg) {
      this.sendMsg2content({ type: 'changeRoute', params: msg });
      this.sendMsg2content({
        type: 'isCollapse',
        params: { collapse: this.isCollapse },
      });
    },
    // 收到子窗口消息
    receiveMsg(info) {
      let { data } = info;
      if (data.source !== 'content') return;
      if (data.action === 'methodRun') {
        const { funName, params = undefined } = data;
        this[funName](params);
      }
    },
    // 收到子窗口消息-弹出消息提示
    showTopMessage(options) {
      this.$message(options);
    },
    // 收到子窗口消息-设置Iframe全屏
    setIframeCover() {
      this.isCoverIframe = true;
    },
    // 收到子窗口消息-取消Iframe全屏
    cancelIframeCover() {
      this.isCoverIframe = false;
    },
  },
};
</script>

<style lang="less" scoped>
.content-box {
  flex: 1;
  overflow: hidden;

  .item {
    position: fixed;
    z-index: 1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100vw;
    height: 100vh;
  }

  .cover_item {
    z-index: 2;
  }
}
</style>
